//
//  TextView+Extention.swift
//  表情键盘
//
//  Created by 李国伟 on 15/12/17.
//  Copyright © 2015年 李国伟. All rights reserved.
//

import UIKit
/// 获取textView上富文本属性
extension UITextView{
    ///  获取textView富文本属性
    ///
    ///  :returns: 带有富文本的字符串
     func appendEmojiString() ->String{
        
        //取到文本属性
        let ts = self.attributedText
        
        //字符串数组
        var strM = String()
        ts.enumerateAttributesInRange(NSRange(location: 0, length: ts.length), options: []) { (dict, range, stop) -> Void in
            
            if dict["NSAttachment"] != nil {
                let attachment = dict["NSAttachment"] as? EmojiAttachment
                strM += attachment?.emotion?.chs ?? ""
            }else{
                let str = (ts.string as NSString).substringWithRange(range)
                strM += str
            }
        }
        return strM
    }
    
    ///  键盘表情显示到文本上
    ///
    ///  :param: emotion emojition模型
    func insertEmoji (emotion: Emoticon){
        
        //如果空不需要操作
        if emotion.isEmpy {
            return
        }
        
        //如果是删除按钮则删除
        if emotion.isRemove {
            deleteBackward()
        }
        
        //替换emoji字符串
        if let emoji = emotion.emoji {
            replaceRange(selectedTextRange!, withText: emoji)
        }
        
        //插入字符串
        if  emotion.png != nil {
            insertEmojiPng(emotion)
        }
        
        delegate?.textViewDidChange!(self)
    }
    
    //设置表情图片
    private func insertEmojiPng(emotion: Emoticon){
        
        //1.创一个带附件的文本
        let attachment = EmojiAttachment(emotion: emotion)
        attachment.image = UIImage(contentsOfFile: emotion.imagePath)
        
        //2.设置图片宽高
        let textline = font?.lineHeight
        attachment.bounds = CGRectMake(0, -4, textline!, textline!)
        
        //设置默认字体大小
        let imgM = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
        imgM.addAttribute(NSFontAttributeName, value: font!, range: NSRange(location: 0, length: 1))
        
        //3.取原文本
        let strM = NSMutableAttributedString(attributedString: attributedText)
        
        //替换图片
        strM.replaceCharactersInRange(selectedRange, withAttributedString: imgM)
        
        //定位
        let range = selectedRange
        
        //反向赋值
        attributedText = strM
        
        //重新定位
        selectedRange = NSRange(location: range.location + 1, length: 0)
    }
}